package spring.netty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;
import spring.AppDemo;
import spring.component.MyController;
import spring.component.MyMapper;

import java.lang.reflect.Method;
import java.util.List;

/**
 * @Description: 创建自定义助手类
 */
// SimpleChannelInboundHandler: 对于请求来讲，其实相当于[入站，入境]

public class CustomHandler extends SimpleChannelInboundHandler<HttpObject> {

    public static AppDemo ctx = new AppDemo("spring");

    public List<Class<?>> controllerFacotry = CustomHandler.ctx.getControllerFacotry();

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg)
            throws Exception {
        // 获取channel


        if (msg instanceof HttpRequest) {

            DefaultHttpRequest request = (DefaultHttpRequest) msg;
            Object invoke = "";

            // 选择 对应的处理器 进行处理请求
            ok:
            for (Class<?> aClass : controllerFacotry) {
                MyController classAnnotation = aClass.getAnnotation(MyController.class);
                String url = classAnnotation.url();
                Method[] methods = aClass.getDeclaredMethods();
                for (Method method : methods) {
                    MyMapper methodAnnotation = method.getAnnotation(MyMapper.class);
                    String method1 = methodAnnotation.method();
                    String newurl = url + methodAnnotation.url();
                    if (method1.equals(request.method().toString()) && newurl.equals(request.uri())) {
                        String typeName = aClass.getName();
                        //获取去除.class之后的文件名
                        typeName = typeName.substring(typeName.lastIndexOf(".") + 1);
                        //将名字(类名,通常为大写开头)的第一个字母转换小写(用它作为key存储工厂中)
                        String key = String.valueOf(typeName.charAt(0)).toLowerCase() + typeName.substring(1);
                        Object bean = CustomHandler.ctx.getBean(key);
                        System.out.println("进入了方法");
                        invoke = method.invoke(bean);
                        break ok;
                    }
                }
            }
            // 定义发送的数据消息
            ByteBuf content = Unpooled.copiedBuffer(invoke.toString(), CharsetUtil.UTF_8);

            // 构建一个http response
            FullHttpResponse response =
                    new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                            HttpResponseStatus.OK,
                            content);
            // 为响应增加数据类型和长度
            response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
            response.headers().set(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes());

            // 把响应刷到客户端
            ctx.writeAndFlush(response);
        }

    }
}
